package com.ljm.sys.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljm.common.enums.DataStatus;
import com.ljm.common.util.StringUtil;
import com.ljm.sys.auth.api.SysAuthRolePermissionApi;
import com.ljm.sys.auth.entity.SysAuthRolePermission;
import com.ljm.sys.auth.mapper.SysAuthRolePermissionMapper;
import com.ljm.sys.auth.service.ISysAuthRolePermissionService;
import com.ljm.sys.org.dto.SysOrgUserDto;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
    * 角色权限 服务实现类
    * </p>
 *
 * @author HuamingChen
 * @since 2019-02-25
 */
@Service
@Transactional
public class SysAuthRolePermissionServiceImpl extends ServiceImpl<SysAuthRolePermissionMapper, SysAuthRolePermission>
        implements ISysAuthRolePermissionService, SysAuthRolePermissionApi {

    @Override
    public void delByRole(String roleCode) {
        QueryWrapper<SysAuthRolePermission> wrapper=new QueryWrapper<>();
        wrapper.eq("role_code",roleCode);
        this.remove(wrapper);
    }

    @Override
    public void saveData(String roleCode, List<String> permissionCodes, SysOrgUserDto userDto) {
        //删除旧关联
        this.delByRole(roleCode);
        List<SysAuthRolePermission> list=new ArrayList<>();
        permissionCodes.stream().forEach(str -> {
            SysAuthRolePermission po=new SysAuthRolePermission();
            po.setCreateTime(LocalDateTime.now());
            po.setCreater(userDto.getLoginName());
            po.setStatus(DataStatus.NORMAL.getCode());
            po.setOrgId(userDto.getOrgId());
            po.setEditor(userDto.getLoginName());
            po.setEditTime(LocalDateTime.now());
            po.setRoleCode(roleCode);
            po.setPermissionCode(str);
            list.add(po);
        });
        this.saveBatch(list);
    }

    @Override
    public List<String> getPermissionByRoleCode(String roleCode) {
        List<String> list=new ArrayList<>();
        QueryWrapper<SysAuthRolePermission> wrapper=new QueryWrapper<>();
        wrapper.eq("role_code",roleCode);
        List<SysAuthRolePermission> permissions=this.list(wrapper);
        if(!StringUtil.isEmpty(permissions)){
            permissions.stream().forEach(item->
                list.add(item.getPermissionCode())
            );
        }
        return list;
    }
}
